// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#include <nebula/util/union_util.h>

#include <cstdint>

#include <nebula/array/data.h>
#include <turbo/base/checked_cast.h>
#include <turbo/log/logging.h>

namespace nebula::union_util {

    int64_t LogicalSparseUnionNullCount(const ArraySpan &span) {
        const auto *sparse_union_type =
                turbo::checked_cast<const SparseUnionType *>(span.type);
                DKCHECK_LE(span.child_data.size(), 128);

        const int8_t *types = span.get_values<int8_t>(1);  // NOLINT
        int64_t null_count = 0;
        for (int64_t i = 0; i < span.length; i++) {
            const int8_t child_id = sparse_union_type->child_ids()[types[span.offset + i]];

            null_count += span.child_data[child_id].is_null(i);
        }
        return null_count;
    }

    int64_t LogicalDenseUnionNullCount(const ArraySpan &span) {
        const auto *dense_union_type = turbo::checked_cast<const DenseUnionType *>(span.type);
                DKCHECK_LE(span.child_data.size(), 128);

        const int8_t *types = span.get_values<int8_t>(1);      // NOLINT
        const int32_t *offsets = span.get_values<int32_t>(2);  // NOLINT
        int64_t null_count = 0;
        for (int64_t i = 0; i < span.length; i++) {
            const int8_t child_id = dense_union_type->child_ids()[types[span.offset + i]];
            const int32_t offset = offsets[span.offset + i];
            null_count += span.child_data[child_id].is_null(offset);
        }
        return null_count;
    }

}  // namespace nebula::union_util
